var curCurPos = -1 ;
var tipCloseWindow = false ; 
var tipCloseWindowMessage = "" ;
(function (d) {
    d['okValue'] = '确定';
    d['cancelValue'] = '取消';
    d['title'] = '消息';
    // [more..]
})(art.dialog.defaults);

//$(document).bind("selectstart",function(){return false;}); 
var closeDialog = false ;

var currentArtDialog ;
var defaultLoadHtml = '<div class="conTop" style="padding:0 20px;"><img src="/assets/images/loading.png" width="35" height="35" alt=""><h2>页面正在载入，请稍候......</h2></div>'; 

//保存当前页面编辑状态下是否有内容需要保存
var unloadPageAlert = false ;

function tipArtPage(title , url , artwidth , lock){
	return tipArtPageWithLock(title , url, artwidth , true);
}

function tipArtPageWithLock(title , url , artwidth , lock){
	var list = art.dialog.list;
	for (var i in list) {
		list[i].close();
	};
	currentArtDialog = art.dialog({ 
		lock: lock,
		id:'curDialog',
		fixed: true,
		title: title,
		width:260,
		padding:'0px 0px',
		drag:true,
		content:defaultLoadHtml,
		initialize: function () {
			var currentDialog = this;
			$.ajax({
				url:url,
				cache:false,
				success: function(data){
					//currentDialog.content(data);
					$('.d-content').empty().html(data);
					
					$('.middleArt').css("width",artwidth);
					//currentDialog.size(artwidth , this.height);
					currentDialog._reset();
					$("input[type='checkbox']").css("border","solid 0px #fff");
					$("input[type='radio']").css("border","solid 0px #fff");
					
				},
				error:  function(xhr, type, s){	
					if(xhr.getResponseHeader("emsg")){
						art.alert(xhr.getResponseHeader("emsg"));
					}
				}
			}).done(function(){
				//var dialogNicescroll = $(".setScroll").niceScroll({cursorcolor:"#d7d7d7"});
			});
		}
	});
}


$(document).ready(function(){
	$('body').on('click', '[data-toggle="ajax"]', function ( e ) {
		var befor = $(this).attr("data-befor");
		if(befor != null && befor != ""){
			var ret = eval(befor);
			if(!ret){
				return false;
			}
		}
		closeDialog = true ;
		var url = $(this).attr("href");
		var title = $(this).attr("title");
		var artwidth = $(this).attr("data-width") ? $(this).attr("data-width") : 750 ;
		var lock = $(this).attr('data-lock') ;

		if(lock == "false"){
			tipArtPageWithLock(title , url , artwidth , false);
		}else{
			tipArtPage(title , url , artwidth);
		}
		return false;
	});
	
	//提交表单并弹出窗口
	$('body').on('click', '[data-toggle="ajax-dialog-form"]', function ( e ) {
		 closeDialog = true ;
		 var url = $(this).attr("href");
		 var title = $(this).attr("title");
		 var form = "#"+$(this).attr("form");
		 var artwidth = $(this).attr("data-width") ? $(this).attr("data-width") : 750 ;
		 currentArtDialog = art.dialog({ 
			lock: true,
			id:'curDialog',
			fixed: true,
			title: title,
			width:260,
			padding:'0px 0px',
			drag:true,
			content:defaultLoadHtml,
			initialize: function () {
				var currentDialog = this;
				
				if($(form).valid()){
					$(form).ajaxSubmit({	  
						url:url,
						success: function(data){
							//currentDialog.content(data);
							$('.d-content').empty().html(data);
							
							$('.middleArt').css("width",artwidth);
							//currentDialog.size(artwidth , this.height);
							currentArtDialog._reset();
						},
						error:function(xhr, type, s){  				
							if(xhr.getResponseHeader("emsg")){
								art.alert(xhr.getResponseHeader("emsg"));
							}
						}
					}); 
				}
			}
		});
		return false;
	});
	/**
	 *表单验证
	 *
	 *
	 */
	$('body').on('submit.form.data-api', '[data-toggle="ajax-form"]', function ( e ) {
		closeDialog = true ;
		var close = $(e.target).attr("data-close");
		if(close){
			closeDialog = false ;
		}
		var formValue = $(e.target) ;
		notification("请稍候，正在加载······",true);	//开始
		if($(this).valid()){
			$(this).ajaxSubmit({	  
				url:formValue.attr("action"),
				success: function(data){
					if(formValue.attr("data-callback")){
						eval(formValue.attr("data-callback")+'($(formValue.attr("data-target")) , data)');
					}else{
						if(formValue.attr("data-target")){
							$(formValue.attr("data-target")).empty().html(data);
						}
					}
					notification("",false);	//结束
					if(closeDialog && currentArtDialog!=null){
						currentArtDialog.close();
					}
					
//					if(currentArtDialog!=null){
//						currentArtDialog._reset();
//					}
					
				},
				error:function(xhr, type, s){  				
					notification("",false);	//结束
				}
			}); 
		}else{
			notification("",false);	//结束
		}	
		return false;
	});

	$('body').on('submit.form.data-api', '[data-toggle="ajax-noclose-form"]', function ( e ) {
		closeDialog = true ;
		var close = $(e.target).attr("data-close");
		if(close){
			closeDialog = false ;
		}
		var formValue = $(e.target) ;
		notification("请稍候，正在加载······",true);	//开始
		if($(this).valid()){
			$(this).ajaxSubmit({	  
				url:formValue.attr("action"),
				success: function(data){

					if(formValue.attr("data-callback")){
						eval(formValue.attr("data-callback")+'($(formValue.attr("data-target")) , data)');
					}else{
						if(formValue.attr("data-target")){
							$(formValue.attr("data-target")).empty().html(data);
						}
					}
					notification("",false);	//结束
				}
			}); 
		}else{
			notification("",false);	//结束
		}		
		return false;
	});

	$('body').on('submit.form.data-api', 'form', function ( e ) {
		if($(this).valid()){
			return true;
		}else{
			return false;
		}
	});
	
	$('body').on('click.a.data-api', '[data-toggle="load"]', function ( e ) {
		closeDialog = true ;
		var href = 	$(this).attr('href') ;
		var target = 	$(this).attr('data-target') ? $(this).attr('data-target') : ".d-content" ;
		if($(target)){
			$(target).empty().html(defaultLoadHtml);		
		}
		//currentDialog.size(260 , 150);
		loadURL(href , target,function(){
			$('.middleArt').css("width","100%");
		});
		return false;
	});

	$('body').on('click.a.data-api', '[data-toggle="delete"]', function ( e ) {
		var href = 	$(this).attr('href') ;
		art.confirm($(this).attr('data-title') , function(){
			location.href =  href;
		} , function(){});
		return false ;
	});	
});

//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadURL(url , panel , callback ){
	loadURLWithTip(url  , panel , callback , true) ;
}

//This function is responsible for ajax loading of pages and the default actions that run everytime a new page is loaded
function loadURLWithTip(url , panel , callback  , tip){
	if(tip == true){
		notification("请稍候，正在加载······",true);	//开始
	}
	$.ajax({
		url:url,
		cache:false,
		success: function(data){
			if(panel){
				$(panel).empty().html(data);
			}
			if(callback){
				callback(data);			
			}
		},
		error:  function(xhr, type, s){	
			if(xhr.getResponseHeader("emsg")){
				art.alert(xhr.getResponseHeader("emsg"));
			}
		}
	}).done(function(){
		if(tip == true){
			notification("",false);	//开始
		}
		//var dialogNicescroll = $(".setScroll").niceScroll({cursorcolor:"#d7d7d7"});
	});
}

function closeR3ArtDialog(){
	if(currentArtDialog){
		currentArtDialog.close();
	}
}

$(window).on('beforeunload',function() {
	if(unloadPageAlert){
		  return "当前页面内容未保存，离开此页面会导致数据丢失，请确认是否离开？";
	}
//	return "你确定关闭?";
});


function createChart(containerid , title , name , data , suffix){
	$(containerid).highcharts({ 		
		chart: {
			type: 'gauge',
			plotBackgroundColor: null,
			plotBackgroundImage: null,
			plotBorderWidth: 0,
			plotShadow: false
		},
		exporting: {
			enabled: false
		},
		title: {	
			text: title
		},
		credits:{
			enabled:false
		},
		pane: {
			startAngle: -150,
			endAngle: 150,
			background: [{
				backgroundColor: {
					linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
					stops: [
						[0, '#FFF'],
						[1, '#333']
					]
				},
				borderWidth: 0,
				outerRadius: '109%'
			}, {
				backgroundColor: {
					linearGradient: { x1: 0, y1: 0, x2: 0, y2: 1 },
					stops: [
						[0, '#333'],
						[1, '#FFF']
					]
				},
				borderWidth: 1,
				outerRadius: '107%'
			}, {
				// default background
			}, {
				backgroundColor: '#DDD',
				borderWidth: 0,
				outerRadius: '105%',
				innerRadius: '103%'
			}]
		},
		   
		// the value axis
		yAxis: {
			min: 0,
			max: 100,
			
			minorTickInterval: 'auto',
			minorTickWidth: 1,
			minorTickLength: 10,
			minorTickPosition: 'inside',
			minorTickColor: '#666',
	
			tickPixelInterval: 30,
			tickWidth: 2,
			tickPosition: 'inside',
			tickLength: 10,
			tickColor: '#666',
			labels: {
				step: 2,
				rotation: 'auto'
			},
			plotBands: [{
				from: 0,
				to: 50,
				color: '#55BF3B' // green
			}, {
				from: 50,
				to: 80,
				color: '#DDDF0D' // yellow
			}, {
				from: 80,
				to: 100,
				color: '#DF5353' // red
			}]        
		},
	
		series: [{
			name: name,
			data: data,
			tooltip: {
				valueSuffix: suffix?suffix:""
			}
		}]
	
	}, 
	// Add some life
	function (chart) {
		if (!chart.renderer.forExport) {
			setInterval(function () {
				var point = chart.series[0].points[0],
					newVal,
					inc = Math.round((Math.random() - 0.5) * 20);
				
				newVal = point.y + inc;
				if (newVal < 0 || newVal > 100) {
					newVal = point.y - inc;
				}
				
				point.update(newVal);
				
			}, 1000);
		}
	});
}
//创建highchar(折线图)
function createChar_area(containerid , title ,unitName, data ){
	$(containerid).highcharts({
		chart: {
			type: 'area'
		},
		title: {
			text: title
		},
		xAxis: {
			type: 'datetime',
			dateTimeLabelFormats: {
				second: '%H:%M:%S'
			}
		},
		yAxis: {
			title: {
				text: title
			},
			labels: {
				formatter: function() {
					return this.value +unitName;
				}
			}
		},
		tooltip: {
			pointFormat: '{point.y}'
		},
		plotOptions: {
			pointStart: Date.UTC(2010, 0, 1),
			pointInterval: 60*1000, // one day
			area: {
				marker: {
					enabled: false,
					symbol: 'circle',
					radius: 2,
					states: {
						hover: {
							enabled: true
						}
					}
				}
			}
		},
		series: data,
		exporting: {
            enabled: false
        }
	});
	
}
function createBarChart(target , type , data , category , title ){
	$(target).highcharts({
		chart: {
			type: type,
			margin: [ 30, 50, 20, 70]
		},
		title: {
			text: title
		},
		xAxis: {
			categories:category
		},
		yAxis: {
			min: 0,
			title: ""
		},
		credits:{
			enabled:false
		},
		legend: {
			enabled: false
		},
		tooltip: {
			pointFormat: '{point.y}'
		},
		series: [{
			data: data
			
		}]
	});
}

function createPieChart(target , data ){
	$(target).highcharts({
		chart: {
            plotBackgroundColor: null,
            plotBorderWidth: null,
            plotShadow: false
        },
        title: {
            text: ''
        },
		credits:{
			enabled:false
		},
        plotOptions: {
			pie: {
				allowPointSelect: true,
				cursor: 'pointer',
				dataLabels: {
					enabled: false
				},
				showInLegend: true
			}
		},
        series: [{
            type: 'pie',
            data: data
        }]
	});
}

/*---------------------------------------------------------------------------------------------------
------------------------------  NOTIFICATIONS MODULE ------------------------------------------------
--------------- TUSHAR KANT SAHAY Copyright 2012 , nanu.clickity@gmail.com --------------------------
---------------------------------------------------------------------------------------------------*/

function notification(_message , type,isshadow){
//**上面这种实现方式如果双击屏蔽层消失，所以采用下面的实现方式
//	if(type){
//		var d = art.dialog({
//			id:"loadData",
//			title:_message,
//			content:'<img src="/assets/images/loading.png"/>',
//			lock: true,
//			fixed: true,
//			width:160,
//			drag:true
//		});
//	}else{
//		//$('.notification').fadeOut();		
//		art.dialog({id:"loadData"}).close();
//	}
	
	if(type){
		
		$('.notification').remove();
		$('.shadow_notification').remove();
		var shadow = "";
		if(isshadow==undefined||isshadow){
			shadow = "<div class=\"d-mask shadow_notification\" style=\"z-index: 100000; position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; overflow: hidden; display: block;\"></div>";
		}
		
		var p = $("<p/>").addClass('notification');
		$('body').append(p);
		$('body').append(shadow);
		var wid = parseInt($(document).width()/2-$(p)[0].offsetWidth/2);
		$(p).css('left',wid.toString()+'px');
		$(p).css('top',$(document).height()*1/3+'px');
		$(p);
	}else{
		if($(".notification").length>0){
			$('.notification').fadeOut();
		}
		if($(".shadow_notification").length>0){
			$('.shadow_notification').fadeOut();
		}
		
	}
}

